<?php

class SaleController  extends Zend_Controller_Action{

    /**
    * @var Cms_Model_Sale
    */
    protected $_saleModel;

    /**
    * @var Zend_Controller_Action_Helper_Url
    */
    protected $_urlHelper;

    /**
    * @var Cms_Service_Authentication
    */
    protected $_authService;

    public function init()
    {
        $this->_saleModel = new Cms_Model_Sale();

        $this->_urlHelper = $this->_helper->getHelper('url');

        $this->_authService = new Cms_Service_Authentication();
    }

    public function saleAction()
    {

        $action = $this->_getParam('do');
        $request = $this->getRequest();

            switch($action){

            	case 'insert':
            		
            		$this->view->backUrl = $this->_urlHelper->url ( array ('do' => 'access' ), 'saleSale', true );
            		$this->view->formAction = $this->_urlHelper->url(array('do'=>'insert'),'saleSale', true);
            		
            		if($request->isPost()){
            		
            			$product = $this->_getParam('product');
            			$sale = $this->_getParam('sale');
            		
            			if(is_array($product)){
            		
            				$dbAdapter = Zend_Registry::get('db');
            				$dbAdapter->exec('SET autocommit = 0');
            				$dbAdapter->exec('LOCK TABLES sale WRITE, saleproduct WRITE, inventory WRITE, admingroup READ');
            				$dbAdapter->beginTransaction();
            		
            				$inventoryModel = new Cms_Model_Inventory();
            				$catalogModel = new Cms_Model_Catalog();
            				
            				unset($sale['saleId']);
            				
            				$saleId = $this->_saleModel->saveSale($sale, $this->_authService->getIdentity()->fullname);
            		
            				$errorProduct = array();
            		
            				foreach ($product as $data) {
            		
            					$data['quantity'] = (int) $data['quantity'];
            		
            					$totalSale = $this->_saleModel->getTotalProductSoldByProductId($data['productId']);
            					$totalPurchases = $inventoryModel->getTotalInventoryByProductId($data['productId']);
            		
            					$availableQuantity = $totalPurchases - $totalSale;
            		
            					if($data['quantity'] <= $availableQuantity){
            		            		
            							$productInfo = $catalogModel->getProductById($data['productId']);
            							
            							$data['saleId'] = $saleId;
            							$data['tax'] = $productInfo->tax;
                                    	$data['discount'] = $productInfo->discount;
            		
            						$this->_saleModel->saveSaleProduct($data);
            		
            					}else{
            						if(!in_array($data['name'], $errorProduct)){
            							$errorProduct[] = $data['name'];
            						}
            					}
            		
            				}
            		
            				if(count($errorProduct) > 0){
            					$dbAdapter->rollback();
            					$dbAdapter->exec('UNLOCK TABLES');
            		
            					$this->view->product = $product;
            					$this->view->sale = $sale;
            					 
            					$returnMessage = "This product(s): '".implode(', ', $errorProduct)."' cannot be processed because the total sale quantity has exceeded the available quantity.";
            					$this->view->returnMessageWarning = array($returnMessage);
            		
            				}else{
            					$dbAdapter->commit();
            					$dbAdapter->exec('UNLOCK TABLES');
            					$this->_helper->flashMessenger->setNamespace ( 'returnMessageSuccess' )->addMessage ( "Success: Sales has been successfully created" );
            					$this->_helper->redirector->gotoRoute ( array ('do' => 'access' ), 'saleSale', true );
            				}
            		
            			}
            		
            		}
            		 
            		$catalogModel = new Cms_Model_Catalog();
            		$this->view->categories = $catalogModel->getCategories();
            		$this->_helper->viewRenderer('savesale');
            		break;
            		
            		case 'update':
            		            		
            			$this->view->backUrl = (null !== $this->_helper->redirectUrl()) ? $this->_helper->redirectUrl() : $this->_urlHelper->url(array('do'=>'access'),'saleSale', true);
            			$this->view->formAction = $this->_urlHelper->url(array('do'=>'update'),'saleSale', true);
            			
            			if($request->isPost()){
            		
            				$product = $this->_getParam('product');
            				$sale = $this->_getParam('sale');
            		
            				$saleId = $sale['saleId'];
            				
            				if(empty($saleId) || (null === ($saleInfo = $this->_saleModel->getSaleById($saleId)))){
            					$this->_helper->redirector->gotoRoute(array('do'=>'access'),'saleSale', true);
            				}
            				
            				if(is_array($product)){
            		
            					//remove the old Sale Product entries
            					$saleProducts = $this->_saleModel->getSaleProducts($saleInfo->saleId);
            					foreach ($saleProducts as $saleProduct) {
            						$this->_saleModel->deleteSaleProduct($this->_saleModel->getSaleProductByEntryId($saleProduct->entryId));
            					}
            					
            					$dbAdapter = Zend_Registry::get('db');
            					$dbAdapter->exec('SET autocommit = 0');
            					$dbAdapter->exec('LOCK TABLES sale WRITE, saleproduct WRITE, inventory WRITE, admingroup READ');
            					$dbAdapter->beginTransaction();
            		
            					$inventoryModel = new Cms_Model_Inventory();
            					$catalogModel = new Cms_Model_Catalog();
            		
            					$this->_saleModel->saveSale($sale, $this->_authService->getIdentity()->fullname, $saleInfo);
            		
            					$errorProduct = array();
            		
            					foreach ($product as $data) {
            		
            						$data['quantity'] = (int) $data['quantity'];
            		
            						$totalSale = $this->_saleModel->getTotalProductSoldByProductId($data['productId']);
            						$totalPurchases = $inventoryModel->getTotalInventoryByProductId($data['productId']);
            		
            						$availableQuantity = $totalPurchases - $totalSale;
            		
            						if($data['quantity'] <= $availableQuantity){
            		
            							$productInfo = $catalogModel->getProductById($data['productId']);
            							
            							$data['saleId'] = $saleId;
            							$data['tax'] = $productInfo->tax;
                                    	$data['discount'] = $productInfo->discount;
                                    	
            							$this->_saleModel->saveSaleProduct($data);
            		
            						}else{
            							if(!in_array($data['name'], $errorProduct)){
            								$errorProduct[] = $data['name'];
            							}
            						}
            		
            					}
            		
            					if(count($errorProduct) > 0){
            						$dbAdapter->rollback();
            						$dbAdapter->exec('UNLOCK TABLES');
            		
            						$this->view->product = $product;
            						$this->view->sale = $sale;
            		
            						$returnMessage = "This product(s): '".implode(', ', $errorProduct)."' cannot be processed because the total sale quantity has exceeded the available quantity.";
            						$this->view->returnMessageWarning = array($returnMessage);
            		
            					}else{
            						$dbAdapter->commit();
            						$dbAdapter->exec('UNLOCK TABLES');
            						$this->_helper->flashMessenger->setNamespace ( 'returnMessageSuccess' )->addMessage ( "Success: Sales has been successfully updated" );
            						$this->_helper->redirector->gotoRoute ( array ('do' => 'access' ), 'saleSale', true );
            					}
            		
            				}
            		
            			}

            			$saleId = $this->_getParam('id');
            			
            			if(empty($saleId) || (null === ($saleInfo = $this->_saleModel->getSaleById($saleId)))){
            				$this->_helper->redirector->gotoRoute(array('do'=>'access'),'saleSale', true);
            			}
            			
            			$this->view->product = $this->_saleModel->getSaleProducts($saleInfo->saleId)->toArray();
            			$this->view->sale = $saleInfo->toArray();
            			             			 
            			$catalogModel = new Cms_Model_Catalog();
            			$this->view->categories = $catalogModel->getCategories();
            			$this->_helper->viewRenderer('savesale');
            			break;
            		            	
                case 'access':
                default:
                	
                	if ($this->_helper->flashMessenger->setNamespace ( 'returnMessageSuccess' )->hasMessages ()) {
                		$this->view->returnMessageSuccess = $this->_helper->flashMessenger->setNamespace ( 'returnMessageSuccess' )->getMessages ();
                	}
                	
                	if ($this->_helper->flashMessenger->setNamespace ( 'returnMessageWarning' )->hasMessages ()) {
                		$this->view->returnMessageWarning = $this->_helper->flashMessenger->setNamespace ( 'returnMessageWarning' )->getMessages ();
                	}
                	
                	$data = array();
                	$partHeadUrl = '';
                	$partPaginationUrl = '';
                	
                	if ($this->_getParam('sort')) {
                		$data['sort'] = $this->_getParam('sort');
                		$partPaginationUrl .= '&sort=' . $this->_getParam('sort');
                	
                		if ($this->_getParam('order')) {
                			$data['order'] = $this->_getParam('order');
                			$partPaginationUrl .= '&order=' . $this->_getParam('order');
                		}else{
                			$data['order'] = 'asc';
                			$partPaginationUrl .= '&order=asc';
                		}
                	}
                	
                	$partHeadUrl .= ($this->_getParam('order') == 'asc') ? '&order=desc' : '&order=asc';
                	
                	if ($this->_getParam('page')){
                		$data['page'] = intval($this->_getParam('page'));
                		$partHeadUrl .= '&page=' . intval($this->_getParam('page'));
                	}else{ //turn on pagination by default
                		$data['page'] = 1;
                	}
                	
                	if ($this->_getParam('limit')) {
                		$data['limit'] = (int) $this->_getParam('limit');
                		$partHeadUrl .= '&limit=' . $this->_getParam('limit');
                		$partPaginationUrl .= '&limit=' . $this->_getParam('limit');
                	}
                	
                	if ($this->_getParam('search')) {
                		$data['search'] = $this->_getParam('search');
                		$partHeadUrl .= '&search=' . $this->_getParam('search');
                		$partPaginationUrl .= '&search=' . $this->_getParam('search');
                	}
                	
                	$this->view->data = $data;
                	$this->view->partHeadUrl = $partHeadUrl;
                	$this->view->partPaginationUrl = $partPaginationUrl;
                	
                	$this->view->sales = ($this->_saleModel->getSales($data)->count() > 0) ? $this->_saleModel->getSales($data) : null;
                	$this->_helper->viewRenderer('listsale');
                	
                	break;
            }

    }

    public function creditAction()
    {
    
    	$action = $this->_getParam('do');
    	$request = $this->getRequest();
    
    	switch($action){
    
    		case 'insert':
    
    			$this->view->backUrl = $this->_urlHelper->url ( array ('do' => 'access' ), 'saleCredit', true );
    			$this->view->formAction = $this->_urlHelper->url(array('do'=>'insert'),'saleCredit', true);
    
    			if($request->isPost()){
    
    				$product = $this->_getParam('product');
    				$sale = $this->_getParam('sale');
    
    				if(is_array($product)){
    
    					$dbAdapter = Zend_Registry::get('db');
    					$dbAdapter->exec('SET autocommit = 0');
    					$dbAdapter->exec('LOCK TABLES creditsale WRITE, creditsaleproduct WRITE, inventory WRITE, admingroup READ');
    					$dbAdapter->beginTransaction();
    
    					$inventoryModel = new Cms_Model_Inventory();
    					$catalogModel = new Cms_Model_Catalog();
    
    					unset($sale['saleId']);
    
    					$saleId = $this->_saleModel->saveCreditSale($sale, $this->_authService->getIdentity()->fullname);
    
    					$errorProduct = array();
    
    					foreach ($product as $data) {
    
    						$data['quantity'] = (int) $data['quantity'];
    
    						$totalSale = $this->_saleModel->getTotalProductSoldByProductId($data['productId']);
    						$totalPurchases = $inventoryModel->getTotalInventoryByProductId($data['productId']);
    
    						$availableQuantity = $totalPurchases - $totalSale;
    
    						if($data['quantity'] <= $availableQuantity){
    
    							$productInfo = $catalogModel->getProductById($data['productId']);
    							 
    							$data['saleId'] = $saleId;
    							$data['tax'] = $productInfo->tax;
    							$data['discount'] = $productInfo->discount;
    
    							$this->_saleModel->saveCreditSaleProduct($data);
    
    						}else{
    							if(!in_array($data['name'], $errorProduct)){
    								$errorProduct[] = $data['name'];
    							}
    						}
    
    					}
    
    					if(count($errorProduct) > 0){
    						$dbAdapter->rollback();
    						$dbAdapter->exec('UNLOCK TABLES');
    
    						$this->view->product = $product;
    						$this->view->sale = $sale;
    
    						$returnMessage = "This product(s): '".implode(', ', $errorProduct)."' cannot be processed because the total sale quantity has exceeded the available quantity.";
    						$this->view->returnMessageWarning = array($returnMessage);
    
    					}else{
    						$dbAdapter->commit();
    						$dbAdapter->exec('UNLOCK TABLES');
    						$this->_helper->flashMessenger->setNamespace ( 'returnMessageSuccess' )->addMessage ( "Success: Credit Sale has been successfully created" );
    						$this->_helper->redirector->gotoRoute ( array ('do' => 'access' ), 'saleCredit', true );
    					}
    
    				}
    
    			}
    			 
    			$catalogModel = new Cms_Model_Catalog();
    			$this->view->categories = $catalogModel->getCategories();
    			$this->_helper->viewRenderer('savecredit');
    			break;
    
    		case 'update':
    
    			$this->view->backUrl = (null !== $this->_helper->redirectUrl()) ? $this->_helper->redirectUrl() : $this->_urlHelper->url(array('do'=>'access'),'saleCredit', true);
    			$this->view->formAction = $this->_urlHelper->url(array('do'=>'update'),'saleCredit', true);
    			 
    			if($request->isPost()){
    
    				$product = $this->_getParam('product');
    				$sale = $this->_getParam('sale');
    
    				$saleId = $sale['saleId'];
    
    				if(empty($saleId) || (null === ($saleInfo = $this->_saleModel->getCreditSaleById($saleId)))){
    					$this->_helper->redirector->gotoRoute(array('do'=>'access'),'saleCredit', true);
    				}
    
    				if(is_array($product)){
    
    					//remove the old Sale Product entries
    					$saleProducts = $this->_saleModel->getCreditSaleProducts($saleInfo->saleId);
    					foreach ($saleProducts as $saleProduct) {
    						$this->_saleModel->deleteCreditSaleProduct($this->_saleModel->getCreditSaleProductByEntryId($saleProduct->entryId));
    					}
    					 
    					$dbAdapter = Zend_Registry::get('db');
    					$dbAdapter->exec('SET autocommit = 0');
    					$dbAdapter->exec('LOCK TABLES creditsale WRITE, creditsaleproduct WRITE, inventory WRITE, admingroup READ');
    					$dbAdapter->beginTransaction();
    
    					$inventoryModel = new Cms_Model_Inventory();
    					$catalogModel = new Cms_Model_Catalog();
    
    					$this->_saleModel->saveCreditSale($sale, $this->_authService->getIdentity()->fullname, $saleInfo);
    
    					$errorProduct = array();
    
    					foreach ($product as $data) {
    
    						$data['quantity'] = (int) $data['quantity'];
    
    						$totalSale = $this->_saleModel->getTotalProductSoldByProductId($data['productId']);
    						$totalPurchases = $inventoryModel->getTotalInventoryByProductId($data['productId']);
    
    						$availableQuantity = $totalPurchases - $totalSale;
    
    						if($data['quantity'] <= $availableQuantity){
    
    							$productInfo = $catalogModel->getProductById($data['productId']);
    							 
    							$data['saleId'] = $saleId;
    							$data['tax'] = $productInfo->tax;
    							$data['discount'] = $productInfo->discount;
    							 
    							$this->_saleModel->saveCreditSaleProduct($data);
    
    						}else{
    							if(!in_array($data['name'], $errorProduct)){
    								$errorProduct[] = $data['name'];
    							}
    						}
    
    					}
    
    					if(count($errorProduct) > 0){
    						$dbAdapter->rollback();
    						$dbAdapter->exec('UNLOCK TABLES');
    
    						$this->view->product = $product;
    						$this->view->sale = $sale;
    
    						$returnMessage = "This product(s): '".implode(', ', $errorProduct)."' cannot be processed because the total sale quantity has exceeded the available quantity.";
    						$this->view->returnMessageWarning = array($returnMessage);
    
    					}else{
    						$dbAdapter->commit();
    						$dbAdapter->exec('UNLOCK TABLES');
    						$this->_helper->flashMessenger->setNamespace ( 'returnMessageSuccess' )->addMessage ( "Success: Credit Sales has been successfully updated" );
    						$this->_helper->redirector->gotoRoute ( array ('do' => 'access' ), 'saleCredit', true );
    					}
    
    				}
    
    			}
    
    			$saleId = $this->_getParam('id');
    			 
    			if(empty($saleId) || (null === ($saleInfo = $this->_saleModel->getCreditSaleById($saleId)))){
    				$this->_helper->redirector->gotoRoute(array('do'=>'access'),'saleCredit', true);
    			}
    			 
    			$this->view->product = $this->_saleModel->getCreditSaleProducts($saleInfo->saleId)->toArray();
    			$this->view->sale = $saleInfo->toArray();
    
    			$catalogModel = new Cms_Model_Catalog();
    			$this->view->categories = $catalogModel->getCategories();
    			$this->_helper->viewRenderer('savecredit');
    			break;
    				
    		case 'access':
    		default:
    			 
    			if ($this->_helper->flashMessenger->setNamespace ( 'returnMessageSuccess' )->hasMessages ()) {
    				$this->view->returnMessageSuccess = $this->_helper->flashMessenger->setNamespace ( 'returnMessageSuccess' )->getMessages ();
    			}
    			 
    			if ($this->_helper->flashMessenger->setNamespace ( 'returnMessageWarning' )->hasMessages ()) {
    				$this->view->returnMessageWarning = $this->_helper->flashMessenger->setNamespace ( 'returnMessageWarning' )->getMessages ();
    			}
    			 
    			$data = array();
    			$partHeadUrl = '';
    			$partPaginationUrl = '';
    			 
    			if ($this->_getParam('sort')) {
    				$data['sort'] = $this->_getParam('sort');
    				$partPaginationUrl .= '&sort=' . $this->_getParam('sort');
    				 
    				if ($this->_getParam('order')) {
    					$data['order'] = $this->_getParam('order');
    					$partPaginationUrl .= '&order=' . $this->_getParam('order');
    				}else{
    					$data['order'] = 'asc';
    					$partPaginationUrl .= '&order=asc';
    				}
    			}
    			 
    			$partHeadUrl .= ($this->_getParam('order') == 'asc') ? '&order=desc' : '&order=asc';
    			 
    			if ($this->_getParam('page')){
    				$data['page'] = intval($this->_getParam('page'));
    				$partHeadUrl .= '&page=' . intval($this->_getParam('page'));
    			}else{ //turn on pagination by default
    				$data['page'] = 1;
    			}
    			 
    			if ($this->_getParam('limit')) {
    				$data['limit'] = (int) $this->_getParam('limit');
    				$partHeadUrl .= '&limit=' . $this->_getParam('limit');
    				$partPaginationUrl .= '&limit=' . $this->_getParam('limit');
    			}
    			 
    			if ($this->_getParam('search')) {
    				$data['search'] = $this->_getParam('search');
    				$partHeadUrl .= '&search=' . $this->_getParam('search');
    				$partPaginationUrl .= '&search=' . $this->_getParam('search');
    			}
    			 
    			$this->view->data = $data;
    			$this->view->partHeadUrl = $partHeadUrl;
    			$this->view->partPaginationUrl = $partPaginationUrl;
    			 
    			$this->view->sales = ($this->_saleModel->getCreditSales($data)->count() > 0) ? $this->_saleModel->getCreditSales($data) : null;
    			$this->_helper->viewRenderer('listcredit');
    			 
    			break;
    	}
    
    }

}
